import React, { createContext, useContext, useState, useEffect } from 'react';
import { theme as antdTheme } from 'antd';

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [isDark, setIsDark] = useState(() => {
    return localStorage.theme === 'dark' || 
      (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches);
  });

  // Ant Design 算法
  const { defaultAlgorithm, darkAlgorithm } = antdTheme;

  useEffect(() => {
    if (isDark) {
      document.documentElement.setAttribute('data-theme', 'dark');
      document.documentElement.classList.add('dark');  // 保留 class 方式以确保兼容性
      localStorage.theme = 'dark';
    } else {
      document.documentElement.setAttribute('data-theme', 'light');
      document.documentElement.classList.remove('dark');
      localStorage.theme = 'light';
    }
  }, [isDark]);

  const toggleTheme = () => {
    setIsDark(!isDark);
  };

  // Ant Design 主题配置
  const antdThemeConfig = {
    algorithm: isDark ? darkAlgorithm : defaultAlgorithm,
    token: {
      // 可以在这里添加自定义token
    },
  };

  return (
    <ThemeContext.Provider value={{ isDark, toggleTheme, antdThemeConfig }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}; 